package com.v5ba.server.event;

import com.v5ba.server.RocketmqEvent;
import com.v5ba.server.dao.UserRepository;
import com.v5ba.server.entity.User;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author yiren
 * @date 2018-08-22
 */
@Component
public class ConsumerEvent {
    @Autowired
    private UserRepository userRepository;

    @EventListener(condition = "#event.topic=='zhanghui_topic' && #event.tag=='tagsA-test'")
    public void msgListen(RocketmqEvent event) {
        DefaultMQPushConsumer consumer = event.getConsumer();
        try {
            System.out.println("ConsumerEvent监听到一个消息达到：" + event.getMsg());

            //TODO 进行业务处理
        } catch (Exception e) {
            if(event.getMessageExt().getReconsumeTimes()<=3){//重复消费3次
                try {
                    consumer.sendMessageBack(event.getMessageExt(), 2);
                } catch (Exception e1) {
                    //TODO 消息消费失败，进行日志记录
                }
            } else {
                //TODO 消息消费失败，进行日志记录

            }
        }
    }

    @EventListener(condition = "#event.topic=='zhanghui_topic' && #event.tag=='tagsA-user-tran'")
    @Transactional
    public void msgListenTran(RocketmqEvent event) {
        long tmp = new Date().getTime() % 2;
        System.out.println("tagsA-test-tran2 执行开始，tmp="+tmp);
        DefaultMQPushConsumer consumer = event.getConsumer();

        System.out.println("ConsumerEvent监听到一个消息达到：" + event.getMsg());
        User user = new User();
        user.setName("张彦辉");
        user.setPhone("18611912657");
        userRepository.save(user);
        long i = 1 / tmp;
        System.out.println("tagsA-test-tran2 执行结束");

    }



}
